package com.sk.waste.app.activitys

import android.Manifest
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.adapters.RecomentAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.enums.IdenEmum
import com.sk.waste.app.enums.PayEmum
import com.sk.waste.app.models.TenderModel
import com.sk.waste.app.utils.BaseUtil
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.utils.PermissionUtil
import com.sk.waste.app.views.PaymentWindow
import com.sk.waste.app.views.SkAlertDialog
import com.sk.waste.app.views.VipNoticeDialog
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException


/**
 *  @time 2025/4/25  17:11
 *  @desc 生意详情
 */
class SyDetailActivity : BaseActiivity() {

    @LCBindView(R.id.ac_root_view)
    private lateinit var rootView: ConstraintLayout

    @LCBindView(R.id.ac_detail_top_img)
    private lateinit var imgTopview: ImageView

    @LCBindView(R.id.ac_detail_expired)
    private lateinit var imgExpired: ImageView

    @LCBindView(R.id.ac_detail_title)
    private lateinit var ttvTitle: TextView

    @LCBindView(R.id.ac_detail_time)
    private lateinit var ttvTime: TextView

    @LCBindView(R.id.ac_detail_price)
    private lateinit var ttvPrice: TextView

    @LCBindView(R.id.ac_detail_area)
    private lateinit var ttvArea: TextView

    @LCBindView(R.id.ac_detail_type)
    private lateinit var ttvType: TextView

    @LCBindView(R.id.ac_detail_content)
    private lateinit var ttvContent: TextView

    @LCBindView(R.id.ac_detail_contact)
    private lateinit var ttvContact: TextView

    @LCBindView(R.id.ac_detail_phone)
    private lateinit var ttvPhone: TextView

    @LCBindView(R.id.ac_detail_recommend)
    private lateinit var recyclerView: RecyclerView

    @LCBindView(R.id.ac_detail_disclaimer)
    private lateinit var ttvDisclaimer: TextView

    @LCBindView(R.id.ac_detail_collection_check)
    private lateinit var imgCollection: CheckBox

    @LCBindView(R.id.ac_detail_collection)
    private lateinit var ttvCollection: TextView

    @LCBindView(R.id.ac_detail_look_detail)
    private lateinit var ttvLookDetail: TextView

    private val tenderList = ArrayList<TenderModel>()
    private lateinit var adapter: RecomentAdapter
    private lateinit var paymentWindow: PaymentWindow

    private lateinit var vipDialog: VipNoticeDialog
    private var alertDialog: SkAlertDialog? = null
    private lateinit var tenderDetail: TenderModel
    private val uerinfo = MyApplication.instance.getUserInfo()
    private var isOnceBuy = false//是否是一次购买
    private var vipOncePrice = "99.00"

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_tender_detail)
        super.onCreate(savedInstanceState)
        setBack()
        setTitleView("生意详情")
        initView()
        initPopuwindow()
        getVipList()
        val tenderId = intent.getStringExtra("tender_id")
        getTenderDetail(tenderId)
    }

    private fun initView() {
        isOnceBuy = false
        recyclerView.layoutManager = LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false)
        adapter = RecomentAdapter(mContext, tenderList, mOnItemClickListener)
        recyclerView.adapter = adapter

        vipDialog = VipNoticeDialog(mContext)
        vipDialog.setOnclickListener(mVipOnclickListener)

        ttvLookDetail.setOnClickListener {

            if (uerinfo!!.isVip() || isOnceBuy) {
                BaseUtil.copyClipboard(mContext, tenderDetail.linkAddress)
                if (tenderDetail.linkAddress.startsWith("【淘宝】")) {
                    startAppWithPackageName("com.taobao.taobao");
                } else if (tenderDetail.linkAddress.startsWith("https://zc-paimai.taobao.com/zc/notice_detail.htm")) {
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(tenderDetail.linkAddress)))
                } else {
                    val intent = Intent(mContext, WebViewActivity::class.java)
//                    val intent = Intent(mContext, AgentWebActivity::class.java)
                    intent.putExtra("extral_title", "原始连接")
                    intent.putExtra("extral_path", tenderDetail.linkAddress)
                    startActivity(intent)
                }
            } else {
                vipDialog.show()
            }
        }

        imgCollection.setOnClickListener {
            if (!LCBaseUtil.isNull(tenderDetail.favoriteId)) {
                unCollection(tenderDetail.favoriteId)
            } else {
                collection(tenderDetail.id)
            }
        }
        ttvCollection.setOnClickListener {
            if (!LCBaseUtil.isNull(tenderDetail.favoriteId)) {
                unCollection(tenderDetail.favoriteId)
            } else {
                collection(tenderDetail.id)
            }
        }
    }

    fun startAppWithPackageName(packageName: String) {
        val intent: Intent? = packageManager.getLaunchIntentForPackage(packageName)
        if (intent != null) {
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or
                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED or
                    Intent.FLAG_ACTIVITY_CLEAR_TOP
            startActivity(intent)
        } else {
            showToast("未获取到连接对应的客户端！")
        }

    }

    private val mOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val postion = args[0] as Int
            val intent = Intent(mContext, SyDetailActivity::class.java)
            intent.putExtra("tender_id", tenderList[postion].id)
            startActivity(intent)
        }

    }

    private val mVipOnclickListener = object : LCInterface.LcOnPnButtonClickLitener {
        override fun onNegetiveClick(vararg args: Any?) {//单次购买
            if (paymentWindow.isShowing) {
                paymentWindow.dismiss()
            } else {
                paymentWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0, vipOncePrice, "单次购买")
            }
        }

        override fun onPositiveClick(vararg args: Any?) {//开通vip
            val intent = Intent(mContext, VipBuyActivity::class.java)
            intent.putExtra("extral_user", IdenEmum.TYPE_USER.identity)
            startActivity(intent)
        }
    }

    /**
     *  @time 2025/4/28  15:13
     *  @desc 支付
     */
    private fun initPopuwindow() {
        paymentWindow = PaymentWindow()
        paymentWindow.init(this)
        paymentWindow.setPopuOnclickListener(object : LCInterface.LcCallBack {
            override fun callBack(vararg args: Any?) {
                val type = args[0] as String
                if (type == "0") //支付宝
                {
                    paymentWindow.creatAliPay(PayEmum.SINGLE_USE.type)
                } else if (type == "1") {//微信
                    paymentWindow.creatWxPay(PayEmum.SINGLE_USE.type)
                } else {
                    isOnceBuy = true
                    LCBaseUtil.showToast(mContext, "支付成功，您的权益已开通可正常使用！")
                }
            }
        })
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 收藏提醒
     */
    private fun showCollectionAlert() {
        if (alertDialog == null) {
            alertDialog = SkAlertDialog(mContext)
        }
        alertDialog!!.setTitleAndContent("收藏提醒", "收藏成功，后续可前往【我的】—【信息收藏】查看")
        alertDialog!!.show("知道了")
    }

    @SuppressLint("SetTextI18n")
    private fun setDetail() {
        getRecommentList()
        Glide.with(mContext).load(NetWorkConfig.NET_URL_IMA_ROOT + tenderDetail.image).transform(CenterCrop(), RoundedCorners(20))
            .error(R.mipmap.img_banner_default).into(imgTopview);
        ttvTitle.text = tenderDetail.title
        ttvTime.text = tenderDetail.startDate+" - "+tenderDetail.endDate
        ttvPrice.text = "￥ ${tenderDetail.price}元"
        ttvArea.text = tenderDetail.address
//        ttvType.text = tenderDetail.categoryName + " - " + tenderDetail.subcategoryName
        ttvType.text = tenderDetail.categoryName
        ttvContent.text = tenderDetail.contentText
        if ("有效" == tenderDetail.status) {
            imgExpired.visibility = View.GONE
            ttvTitle.setTextColor(mContext.getColor(R.color.color_text_deep))
        } else {
            imgExpired.visibility = View.VISIBLE
            ttvTitle.setTextColor(mContext.getColor(R.color.color_text_gray))
        }
        if (uerinfo!!.isVip()) {
            ttvContact.text = "联系人：" + tenderDetail.person
            ttvPhone.text = "手机号：" + tenderDetail.phone
        } else {
//            ttvContact.text = "联系人：" + tenderDetail.person.substring(0, 1) + "**"
//            ttvPhone.text = "手机号：" + tenderDetail.phone.substring(0, 3) + "********"
            ttvContact.text = "联系人：" + BaseUtil.getNameHideStr(tenderDetail.person)
            ttvPhone.text = "手机号：" + BaseUtil.getPhoneHideStr(tenderDetail.phone)
        }

        ttvPhone.setOnClickListener {
            if (uerinfo.isVip()) {
                if (!tenderDetail.phone.contains(",") && !tenderDetail.phone.contains("，")) {
                    BaseUtil.callPhone(mContext, tenderDetail.phone)
                }
            }
        }

        if (!LCBaseUtil.isNull(tenderDetail.favoriteId)) {
            imgCollection.isChecked = true
        } else {
            imgCollection.isChecked = false
        }
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 详情
     *  @param url
     */
    private fun getTenderDetail(tenderId: String?) {
        if (tenderId.isNullOrEmpty()) {
            return
        }
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_SYDETAIL
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("id", tenderId)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    if (success) {
                        tenderDetail = TenderModel().apply { getModelInfo(data) }
                        runOnUiThread { setDetail() }
                        LCLogger.d(TAG, "获取成功！,数据：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 推荐
     *  @param url
     */
    private fun getRecommentList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_SYLIST
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", 10)
        params.put("pageNo", 1)
        params.put("contentText", "")
        params.put("categoryIds", tenderDetail.categoryId)
        params.put("subcategoryIds", tenderDetail.subcategoryId)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    val rows = data.getJSONArray("rows")
                    if (success) {
                        for (index in 0 until rows.length()) {
                            val item = TenderModel().apply { getModelInfo(rows.getJSONObject(index)) }
                            tenderList.add(item)
                        }
                        runOnUiThread { adapter.notifyDataSetChanged() }
                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 收藏
     *  @param url
     */
    private fun collection(tenderId: String?) {
        if (tenderId.isNullOrEmpty()) {
            return
        }
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_COLLCTION
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("wasteInformationId", tenderId)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
//                    val code = jsonObject.getInt("code")
//                    val data = jsonObject.getJSONObject("data")
                    if (success) {
                        getTenderDetail(tenderId)
                        runOnUiThread { showCollectionAlert() }
                        LCLogger.d(TAG, "获取成功！,数据：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 取消收藏
     *  @param url
     */
    private fun unCollection(favoriteId: String?) {
        if (favoriteId.isNullOrEmpty()) {
            return
        }
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_UNCOLLCTION
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("id", favoriteId)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
//                    val code = jsonObject.getInt("code")
//                    val data = jsonObject.getJSONObject("data")
                    if (success) {
                        getTenderDetail(tenderDetail.id)
                        showToast("已取消！")
                        LCLogger.d(TAG, "获取成功！,数据：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/8/8  13:58
     *  @author Im_jingwei
     *  @desc 验证支付宝支付结果
     */
    private fun verifyAliPay(orderNo: String) {
        showProgress("正在验证支付结果...")
        val httpUtil = OkHttpUtil()
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_ALIPAY_QUERY
        httpUtil.httpRequestGet(url, token, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                LCBaseUtil.showToast(mContext, "支付宝订单验证失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    val jsonObject = JSONObject(response)
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    if (code == 200) {
                        val state = data.getString("status")
                        if (state == "TRADE_SUCCESS") {
                            LCBaseUtil.showToast(mContext, "支付结果验证成功，你已经是VIP了！")
                        }
                    } else {
                        LCBaseUtil.showToast(mContext, "支付宝订单验证异常,请联系客服处理。")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "支付宝订单验证失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/9/26  9:35
     *  @author Im_jingwei
     *  @desc 获取价格列表
     */
    private fun getVipList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_VIP_LIST
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]

        val httpUtil = OkHttpUtil()
        httpUtil.httpRequestGet(url, token, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val data = jsonObject.getJSONArray("data")
                    if (success) {
                        if (data.length() > 0) {
                            val json = data.getJSONObject(0)
                            vipOncePrice = json.getString("price")
                        }
                    } else {
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                }
            }
        })
    }


}